<template>
  <div>
    <!--        搜索区域-->
    <el-row :gutter="24" class="el-rowss">
      <el-col :md="6" :sm="12">
        <el-input v-model="role.code" placeholder="请输入代码"
                  :clearable="(role.code == null||role.code == '')?false:true">
        </el-input>
      </el-col>
      <el-col :md="6" :sm="12">
        <el-input v-model="role.name" placeholder="请输入姓名"
                  :clearable="(role.name==null||role.name=='')?false:true">
        </el-input>
      </el-col>
      <el-col :md="6" :sm="12">
        <el-button type="primary" @click="getRoleList" icon="el-icon-search">搜索</el-button>
      </el-col>
      <el-col :md="6" :sm="12">
        <el-button type="primary" icon="el-icon-plus" @click="addRole">添加角色</el-button>
      </el-col>
    </el-row>

    <!--       卡片区域-->
    <el-card>
      <el-table :data="roleList" border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="角色编码" prop="code"></el-table-column>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column label="描述" prop="discribe"></el-table-column>
        <el-table-column label="操作" class="el-table-column">
          <template #default="scope">
            <el-button type="text" @click="editRole(scope.row.code)">修改</el-button>
            <el-button type="text"  @click="delRole(scope.row.code)">删除</el-button>
            <el-button type="text"  @click="RoleUsers(scope.row.code)">用户</el-button>
            <el-button type="text" @click="jurisdiction(scope.row.code)">权限授权</el-button>
            <el-button type="text" @click="jurisMenu(scope.row.code)">角色菜单分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页列表-->
      <PagePagination :page="role" @pageChanged="pageChange"></PagePagination>
    </el-card>

    <!--        添加/修改弹出框-->
    <el-drawer v-model="roleDialogVisible" size="30%"
               :title="(this.role.code == null||this.role.code=='')?'添加':'修改'">
      <el-form :model="roleForm"  label-width="100px" :rules="rules"
               ref="roleForm">
        <el-form-item label="代码：" prop="code">
          <el-input v-model="roleForm.code" :disabled="disable"></el-input>
        </el-form-item>
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="roleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="discribe">
          <el-input v-model="roleForm.discribe"></el-input>
        </el-form-item>
        <el-button @click="roleDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="roleSumbit('roleForm')">确定</el-button>
      </el-form>
    </el-drawer>
    <!--        权限信息弹出框-->
    <el-drawer v-model="jurisdictionDialog" size="20%" title="角色权限列表" >
      <el-tree class="el-tree" :data="roleJurisdiction"
               :props="jurisdictionProps" ref="treeRef"
               default-expand-all  node-key='id'
               :default-checked-keys="roleTree"
               show-checkbox>
      </el-tree>
      <el-button type="info" @click="jurisdictionDialog = false">取消</el-button>
      <el-button type="success" @click="treeBtn">确定</el-button>
    </el-drawer>
    <!--菜单分配弹窗-->
    <el-drawer v-model="menuDialog" size="20%" title="菜单分配弹窗" >
      <el-tree class="el-tree" :data="menuDrawer"
               :props="menuDrawerProps" ref="menuRef"
               default-expand-all  node-key='id'
               :default-checked-keys="menuTree"
               show-checkbox>
      </el-tree>
      <el-button type="info" @click="menuDialog = false">取消</el-button>
      <el-button type="success" @click="menuBtn()">确定</el-button>
    </el-drawer>

    <!--对应角色的用户列表-->
    <el-drawer  v-model="roleUserdrawer" :with-header="false" size="50%">
      <el-row :gutter="24" class="el-rowss">
        <el-col :md="6" :sm="12"><el-input v-model.trim="roleUser.phone" placeholder="请输入手机号"></el-input></el-col>
        <el-col :md="6" :sm="12"><el-input v-model.trim="roleUser.nickname" placeholder="请输入用户昵称"></el-input></el-col>
        <el-col :md="4" :sm="12"><el-button type="primary" icon="el-icon-search">搜索</el-button></el-col>
        <el-col :md="4" :sm="12"><el-button type="primary" icon="el-icon-plus">添加用户</el-button></el-col>
        <el-col :md="4" :sm="12"><el-button type="danger" :disabled="show" @click="deleteUserRole">批量删除</el-button></el-col>
      </el-row>
      <el-card>
        <el-table :data="RoleUser" @selection-change="selectionChange" max-height="750">
          <el-table-column type="selection"></el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="手机号" prop="phone" ></el-table-column>
          <el-table-column label="昵称" prop="nickname" ></el-table-column>
          <el-table-column label="姓名"  prop="realname"></el-table-column>
          <el-table-column label="性别" prop="sex"></el-table-column>
          <el-table-column label="状态" prop="state">
            <template #default="scope">
              <span>{{(scope.row.state== 1)?'正常':'禁用'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" class="colbutton">
            <template #default="scope">
              <el-button size="mini" type="text" @click="delRoleUser(scope.row.roleUserId)">删除</el-button>
              <el-button size="mini" type="text">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页列表-->
        <PagePagination :page="roleUser" @pageChanged="roleUserChange"></PagePagination>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
import PagePagination from "../../components/PagePagination";
export default {
  name: "Roles",
  components: {PagePagination},
  data(){
    return{
      //获取到的角色权限列表
      roleJurisdiction:[],//保存角色权限列表数据
      jurisdictionProps:{
        children:'children',
        label:'describes'
      },
//菜单分配
      menuDrawer: [],//保存菜单列表数据
      menuDialog:false,
      menuDrawerProps:{
        children:'children',
        label:'name'
      },
      menuTree: [],//保存选中的菜单id
//----------------------------
      roleTree:[],//保存默认选中的勾选框的id
      jurisdictionDialog:false,//是否角色权限弹出框
      disable:false,//添加或修改弹框中的code是否显示
      // 角色添加/修改表单规则
      roleForm:{
        code: '',
        name: '',
        discribe: ''
      },
      rules:{
        code: [
          {required: true, message: '请输入代码', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ]
      },
      roleDialogVisible: false,//是否添加\修改弹出框
      role: {
        code: '',
        name: '',
        discribe: '',
        pageNo: 1,
        pageSize: 10,
        pageNum: null,//请求过来的当前页数
        totalPage: null,//请求过来的总页数
        count: null,//请求过来的总条数
        roleCode: ''
      },
      roleList: [],//保存角色列表数据

      RoleUser: [],//查询对应角色的用户列表
      roleUserdrawer: false,
      name:'',
      show: true,
      deleteRoleUser: [],//用于存放批量删除时的数据
      roleUser: {
        phone: '',
        nickname: '',
        realname: '',
        sex: '',
        count: null,
        pageNo: 1,
        pageSize: 5,
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    //接收传过来的page改变
    pageChange(val) {
      this.role.pageNo = val.pageCno;
      this.role.pageSize = val.pageCsize;
      this.getRoleList(this.role)
    },
    roleUserChange(val) {
      this.roleUser.pageNo = val.pageCno;
      this.roleUser.pageSize = val.pageCsize;
      this.RoleUsers(this.name)
    },
    //获取角色列表
    async getRoleList() {
      const par = {
        code: this.role.code,
        name: this.role.name,
        pageNo: this.role.pageNo,
        pageSize: this.role.pageSize
      }
      await this.$api.system.getRole(par).then(res => {
        //console.log('这是角色列表：', res.data);
        this.roleList = res.data.data;
        this.role.count =  res.data.count;
        this.role.pageNum = res.data.pageNum;
        this.role.totalPage =  res.data.totalPage;
      })
    },

    // 添加角色按钮事件
    addRole() {
      this.role = {};
      this.roleDialogVisible = true;
    },
    // 修改角色信息按钮事件
    async editRole(val){
      this.roleDialogVisible=true;
      this.role.code=val
      //console.log(this.role.code);
      await  this.$api.system.codeRoleSelect(this.role.code, this.roleForm).then(res=>{
        if(res.status == 200){
          this.disable=true;
          this.roleForm=res.data.data
          console.log(this.roleForm);
        }else{
          this.$message.error('失败')
        }

      })
    },
    // 添加/修改角色信息的弹出框
    async  roleSumbit(fromName) {
      await this.$refs[fromName].validate((valid) => {
        if (valid) {
          const code = this.role.code;
          console.log(code)
          if (code == null||code == '') {
            this.$api.system.addRole(this.roleForm).then(res => {
              //console.log(res.data);
              if (res.data.code === 200){
                this.$message.success(res.data.message);
                this.getRoleList();
                this.roleDialogVisible = false;
              }else {
                this.$message.error('添加失败！！！角色可能已存在')
              }
            })
          }else {
            this.$api.system.editRole(this.roleForm).then(res => {
              // this.disable=true;
              if (res.data.code === 200) {
                this.$message.success('修改成功');
                this.role.code = null;
                this.getRoleList()
                this.roleDialogVisible = false;
              }else {
                this.$message.error('修改失败')
              }
            })
          }
        }else {
          return false
        }

      })
    },
    // 删除角色
    async  delRole(valid) {
      await this.$confirm('是否删除？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.system.deleteRole(valid).then(res=>{
          if(res.data.code === 200){
            this.$message.success('删除成功')
            this.getRoleList()
          }else {
            this.$message.error('删除失败')
          }
        }).catch(err =>  this.$message.error(res.message))
      }).catch(err => {
        this.$message.error('取消删除操作')
      })
    },

//角色权限列表
    async jurisdiction(val){
      //   console.log('你点击了权限分配');
      this.roleTree = [];
      this.role.roleCode = val;
      const par = {
        roleCode:val
      }
      await this.$api.system.RoleJurisdiction(par).then(res=>{
        if (res.data.code === 200){
          //console.log(res.data.data);
          this.roleJurisdiction = res.data.data;
          this.getTreeKey(this.roleJurisdiction, this.roleTree)
          this.jurisdictionDialog = true
        }else{
          this.$message.error(res.data.message)
        }
      });

    },
    //采用递归的形式获取当前角色所有权限下的id
    // 同时将得到的节点保存到数组roleTree中
    getTreeKey(node,array){
      // if(!node.children){
      //       return array.push(node.id)
      // }
      // node.children.forEach(item=>{
      //     this.getTreeKey(item,array)
      // })
      for (let i = 0; i < node.length; i++) {
        let item = node[i];
        if (item.children != null && item.children.length > 0){
          this.getTreeKey(item.children, array);
        }else {
          if(item.roleCode != null) {
            // item.roleCode = item.id
            console.log('....=',item.id);
            array.push(item.id);
          }
        }
      }
    },
    // 权限分配弹框中的确定按钮
    treeBtn(){
      const treeArray = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log('treeArray', treeArray);
      this.roleTree = treeArray;
      var para={
        roleCode:this.role.roleCode,
        juriIds:this.roleTree.toString()
      };
      //console.log('这是传过来的 roleCode=', para.roleCode);
      //console.log('这是传过来的juriIds=', para.juriIds);
      this.$api.system.getRoleAllocation(para).then(res=>{
        if (res.data.code===200){
          //console.log('成功');
          //console.log(res.data);
          //this.$message.success('成功1111');
          this.jurisdictionDialog = false;

        }
      });

    },

//角色菜单分配
    async jurisMenu(val) {
      //console.log(val)
      this.menuTree = [];
      this.role.roleCode = val
      var par = {
        category: 0,
        roleCode: this.role.roleCode
      }
      this.$api.system.RoleMenuJurisdiction(par).then(res => {
        if (res.data.code === 200) {
          this.menuDrawer = res.data.data;
          this.roleMenu(this.menuDrawer, this.menuTree);
        }else return this.$message.error('错误')
        this.menuDialog = true;
      }).catch(err => {
        this.$message.error('分配出错咯')
      })
    },
    //得到当前角色所拥有的菜单列表
    roleMenu(node,menuArr) {
      //for (let i =0;i<node.length;i++){
      //  let item = node[i];
      //  if (item.children !=null&& item.children.length > 0){
      //    this.roleMenu(item.children,menuArr)
      //  }else {
      //    if (item.roleCode != null){
      //      //console.log('item.id=', item.id)
      //      menuArr.push(item.id);
      //    }
      //  }
      //}
      for (let i =0;i<node.length;i++){
        let item = node[i];
        if (item.children == null|| item.children.length < 0){
          if (item.roleCode != null){
            menuArr.push(item.id);
          }
        }else {
          this.roleMenu(item.children,menuArr)
        }
      }
    },
    async  menuBtn() {
      const menuArray = [
        ...this.$refs.menuRef.getCheckedKeys(),
        ...this.$refs.menuRef.getHalfCheckedKeys()
      ];
      this.menuTree = menuArray;
      var par = {
        roleCode: this.role.roleCode,
        category: 0,
        menuIds: this.menuTree.toString()
      }
      await this.$api.system.RoleMenu(par).then(res => {
        console.log(res)
        if (res.status == 200){
          this.menuDialog = false;
        }
      })
    },


    //查看当前角色的用户
    RoleUsers(val) {
      console.log(val)
      this.name = val
      var par = {
        roleCode: val,
        pageNo: this.roleUser.pageNo,
        pageSize: this.roleUser.pageSize
      }
      this.$api.system.getRoleUser(par).then(res => {
          console.log(res.data.data);
          this.RoleUser = res.data.data
          this.roleUser.count = res.data.count
          this.roleUserdrawer = true
        }
      ).catch()
      console.log('查看当前角色的用户')
    },

    selectionChange(data) {
      if (data.length > 0) {
        this.show = false;
        let ids = [];
        for (let i=0;i < data.length;i++) {
          let item = data[i];
          ids.push(item.roleUserId);
        }
        this.deleteRoleUser = ids.join(',');
      }else this.show = true
    },
    //批量删除删除角色里的用户
    async deleteUserRole () {
      console.log('你点击了删除');
      await this.$confirm('是否删除？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let par = {ids: this.deleteRoleUser};
          this.$api.system.deleteRoleUser(par).then(res=>{
            console.log(res);
            if(res.data.code === 200){
              this.$message.success('删除成功')
              this.RoleUsers(this.name)
            }else {
              this.$message.error('删除失败')
            }
          }).catch(err =>  this.$message.error(res.data.message));
        })
        .catch(() => {
          this.$message.error('取消删除操作')
        })
    },
    //单个删除角色里的用户
    delRoleUser(val) {
      console.log(val)
      this.deleteRoleUser = val;
      this.deleteUserRole();
    },
  },

}
</script>

<style scoped>
.el-rowss{
  margin: 15px;
}
.el-rowss .el-col .el-input {
  margin: 10px;
}
.el-rowss .el-col .el-button {
  margin: 5px;
}
.el-header .el-row .el-button{
  clear: both;
}
.el-table-column{
  text-align: center;
  margin: 5px;
}
.el-table-column button{
  width: 30px;
}
/*.el-drawer .el-form .el-button{*/
/*float: right;*/
/*  margin: 5px;*/
/*}*/
/*.el-drawer  .el-button{*/
/*  float: right;*/
/*  margin: 5px;*/
/*}*/

.el-pagination{
  float: right;
  margin-top: 5px;
  margin-bottom: 5px;
}
</style>